﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing;
using System.IO;
using System.Threading;
using System.Text;
using Business;
using System.Web.Security;
public partial class admin_Create_Machine : System.Web.UI.Page
{
    //Create new decryption and image editor object
    Decryption objdec = new Decryption();
    ImageEditor objimg = new ImageEditor();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["MachineTypeID"] != null)
        {
            var dpMachinetype = (DropDownList)FormViewMachine.FindControl("MachineTypeDropDownList");
            dpMachinetype.SelectedIndex = dpMachinetype.Items.Count - 1;
        }
    }
    /// <summary>
    /// Handles the DataBound event of the FormViewMachine control.
    /// Set the Site name, if the page open from View_Site.aspx
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void FormViewMachine_DataBound(object sender, EventArgs e)
    {
        PlaceHolder siteNamePH = FormViewMachine.FindControl("siteNamePlaceHolder") as PlaceHolder;
        DropDownList siteNameDDL = FormViewMachine.FindControl("siteNameDropDownList") as DropDownList;
        string site_id = ""; ;
        try
        {
            site_id = objdec.DecodeUrl(Request.QueryString["site_id"].ToString());
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        if (site_id != "")
        {
            siteNamePH.Visible = false;
            siteNameLabel.Visible = true;
            siteNameDDL.SelectedIndex = siteNameDDL.Items.IndexOf(siteNameDDL.Items.FindByValue(site_id));
            siteNameLabel.Text = "for site: " + siteNameDDL.SelectedItem.Text;

        }
    }
    /// <summary>
    /// Handles the Click event of the uploadButton control.
    /// Resize the original image to certain size
    /// Save the image to the path folder
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void uploadButton_Click(object sender, EventArgs e)
    {
        TextBox photoTextBox = FormViewMachine.FindControl("photoTextBox") as TextBox;
        FileUpload photoFileUpload = FormViewMachine.FindControl("photoFileUpload") as FileUpload;
        Label statusLabel = FormViewMachine.FindControl("statusLabel") as Label;
        System.Web.UI.WebControls.Image photoImage = FormViewMachine.FindControl("photoImage") as System.Web.UI.WebControls.Image;

        //to retrieve only Filename from the complete path
        int extractPos = photoFileUpload.FileName.LastIndexOf("\\") + 1;
        string photoFileName = photoFileUpload.FileName.Substring(extractPos, photoFileUpload.FileName.Length - extractPos);
        if (photoFileName.IndexOf("/") >= 0 || photoFileName.IndexOf("\\") >= 0)
        {
            //We found a / or \
            Response.End();
        }

        if (photoFileUpload.HasFile)
        {
            //to check file extension is JPG.
            string fileExt = System.IO.Path.GetExtension(photoFileUpload.FileName);
            if (fileExt.ToUpper() == ".JPG")
            {

                //resize image before uploading - start.
                try
                {
                    System.Drawing.Image imageToBeResized = System.Drawing.Image.FromStream(photoFileUpload.PostedFile.InputStream);
                    int height = 0;
                    int width = 0;
                    // check if image is in potrait or landscape scale.
                    if (objimg.isPortrait(imageToBeResized))
                    {
                        height = 800;
                        width = 600;
                    }
                    else
                    {
                        height = 600;
                        width = 800;
                    }

                    Bitmap bitmap = objimg.ResizeThisImage(width, height, imageToBeResized);
                    //Save uploaded file to server at the in the Pics folder.
                    bitmap.Save(Request.PhysicalApplicationPath
                                    + "photos\\" + photoFileName, ImageFormat.Jpeg);
                    statusLabel.Text = " File Name: " + photoFileUpload.PostedFile.FileName + "<br>" +
                            " File Size: " + photoFileUpload.PostedFile.ContentLength + " kb<br>" +
                            " File Type: " + photoFileUpload.PostedFile.ContentType;
                    photoImage.Visible = true;
                    photoImage.Attributes.Add("Width", Convert.ToString(0.2 * bitmap.Width));
                    photoImage.Attributes.Add("Height", Convert.ToString(0.2 * bitmap.Height));
                    photoImage.ImageUrl = "../photos/" + photoFileName;

                    bitmap.Dispose();
                    imageToBeResized.Dispose();

                    //bind photo file name to textbox.
                    photoTextBox.Text = photoFileName;
                    Button removeButton = FormViewMachine.FindControl("removeButton") as Button;
                    removeButton.Visible = true;

                }
                catch (ArgumentException)
                {
                    statusLabel.Text = "Unknown image file!";
                }
                catch (ThreadAbortException)
                {

                }
                catch (Exception ex)
                {
                    statusLabel.Text = "Unknown error: " + ex;
                }
            }
            else
            {
                statusLabel.Text = "Only 'jpeg' files allowed!";
            }
        }
        else
        {
            statusLabel.Text = "You have not specified a file.";
        }
    }
    /// <summary>
    /// Handles the Click event of the removeButton control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void removeButton_Click(object sender, EventArgs e)
    {
        TextBox photoTextBox = FormViewMachine.FindControl("photoTextBox") as TextBox;
        System.Web.UI.WebControls.Image photoImage = FormViewMachine.FindControl("photoImage") as System.Web.UI.WebControls.Image;
        photoTextBox.Text = "Not Available";
        photoImage.Visible = false;
    }
    /// <summary>
    /// Handles the Click event of the InsertCancelButton control.
    /// Go to the source page.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void InsertCancelButton_Click(object sender, EventArgs e)
    {
        string site_id = "";
        try
        {
            site_id = objdec.DecodeUrl(Request.QueryString["site_id"].ToString());
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        if (site_id != "")
        {
            Server.Transfer("View_Site.aspx?site_id=" + site_id);
        }
        else
        {
            Server.Transfer("Mng_Machine.aspx");
        }
    }
    /// <summary>
    /// Handles the ItemInserted event of the FormViewMachine control.
    /// Go to the source page.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.FormViewInsertedEventArgs"/> instance containing the event data.</param>
    protected void FormViewMachine_ItemInserted(object sender, FormViewInsertedEventArgs e)
    {
        string site_id = "";
        try
        {
            site_id = objdec.DecodeUrl(Request.QueryString["site_id"].ToString());
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        if (site_id != "")
        {
            Server.Transfer("View_Site.aspx?site_id=" + site_id);
        }
        else
        {
            Server.Transfer("Mng_Machine.aspx");
        }
    }
    protected void InsertButton_Click(object sender, EventArgs e)
    {
        TextBox photoTextBox = FormViewMachine.FindControl("photoTextBox") as TextBox;
        if (photoTextBox.Text == string.Empty || photoTextBox.Text == "" || photoTextBox.Text == "&nbsp;" || photoTextBox.Text == "Not Available")
        {
            photoTextBox.Text = "NotAvailable.jpg";
        }
    }
    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
    {


        Session.Contents.Remove("UserDetails");
        Session.Abandon();
        Session.Contents.RemoveAll();
        FormsAuthentication.SignOut();
        Response.Redirect("../Default.aspx");
    }

    protected void OnMachineInserted(object sender, ObjectDataSourceStatusEventArgs e)
    {
        var tbmachineName = (TextBox)FormViewMachine.FindControl("machineNameTextBox");
        string machineName = tbmachineName.Text;
        var dpSite = (DropDownList)FormViewMachine.FindControl("siteNameDropDownList");
        int siteID;
        Int32.TryParse(dpSite.SelectedValue, out siteID);
        string selectIdQry = "select * from Machines where machineName ='" + machineName + "'and site_id ='" + siteID +
                             "'";
        var dtMachine = new CreateConn().SQLConnDataTable(selectIdQry);
        int insertedMachine_ID = 0;
        while (dtMachine.Rows.Count > 0)
        {
            Response.Write("<SCRIPT LANGUAGE = JavaScript>alert('Hello this is an Alert')</SCRIPT>");
            //            Response.Write("<script language=javascript> alert('Create new machine has succeed.Redirecting to machine view page...')</script>");
            Int32.TryParse(dtMachine.Rows[0]["machine_id"].ToString(), out insertedMachine_ID);
            Response.Redirect("View_Machine.aspx?machine_id=" + insertedMachine_ID);
            break;
        }
        Response.Write(
            "<script language=javascript> alert('Create new machine has failed.Redirecting to machine view page...')</script>");

    }

}
